console.log("here");

var POINTS_CORRECT = 2;
var POINTS_GUESSED = 1;
var POINTS_UNGUESSED = 3;

var POINTS_TO_WIN = 25;


var TEST_MODE = false;

function goFirst() {
	
	var id = gapi.hangout.getParticipantId();
	
	var delta = {};
	delta['turn'] = '0';
	delta['turnId'] = id;
	delta['firstPlayer'] = id;
	gapi.hangout.data.submitDelta(delta);
}

function determineTurn() {	
	console.log('Determining Turn');
	
	var id = gapi.hangout.getParticipantId();

	console.log('This is not the first turn.');
	
	var firstPlayer = gapi.hangout.data.getState()['firstPlayer'];
	
	if (firstPlayer == id) {
		
		var p = gapi.hangout.getParticipants();
	
		var turn = parseInt(gapi.hangout.data.getState()['turn']);
		turn = turn + 1;
		if (turn >= p.length) {
			turn = 0;
		}
		
		
		var qp = p[turn];
		
		var delta = {};
		delta['turn'] = ''+turn;
		delta['turnId'] = qp.hangoutId;
		gapi.hangout.data.submitDelta(delta);
	}
}


function createContentBeforeQuestion() {
	   
	document.getElementById('startDiv').style.display = 'none';
	
	var turnId = gapi.hangout.data.getState()['turnId'];
	var turnP = gapi.hangout.getParticipantById(turnId);
	
	var id = gapi.hangout.getParticipantId();
	
	if (id == turnId) {
		document.getElementById('questionBoxDiv').style.display = 'block';
	}
	else {
		document.getElementById('questionDisplayDiv').innerHTML = turnP.displayName + ' is writing a question.';
		document.getElementById('questionDisplayDiv').style.display = 'block';
	}
	
}

function questionSubmitted() {
	var question = document.getElementById('questionText').value;
	
	console.log("question submitted: "+question);
	
	if (question.length > 5) {
		gapi.hangout.data.submitDelta({'question': question});
	}
}

function createContentAfterQuestion() {
	
	console.log("createContentAfterQuestion()");
	
	document.getElementById('questionBoxDiv').style.display = 'none';
	document.getElementById('questionDisplayDiv').innerHTML = '<b>Question: </b><br/>' + gapi.hangout.data.getState()['question'];
	document.getElementById('questionDisplayDiv').style.display = 'block';
	
	document.getElementById('answerBoxDiv').style.display = 'block';
}

function answerSubmitted() {
	var id = gapi.hangout.getParticipantId();
	
	var answer = document.getElementById('answerText').value;
	if (answer.length > 0) {
		console.log("Answer submitted: "+answer);
		
		var key = 'answer_' + id;
		
		var delta = {};
		delta[key] = answer;
		
		gapi.hangout.data.submitDelta(delta);
		
		document.getElementById('answerSubmitDiv').style.display = 'block';
	}
}

function createContentAfterAnswer() {
	
	var p = gapi.hangout.getParticipants();
	
	var sourceId = gapi.hangout.getParticipantId();
	
	console.log(p.length + " participants");
	
	for (var i = 0; i < p.length; i++) {
		var key = 'answer_' + p[i].hangoutId;
		if (!gapi.hangout.data.getState()[key]) {
			console.log("Not all answers have been recieved. Missing: "+key);
			return;
		}
	}
	
	document.getElementById('answerSubmitDiv').style.display = 'none';
	document.getElementById('answerBoxDiv').style.display = 'none';
	
	console.log("all answers submitted");
	
	var answers = new Array();
	for (var i = 0; i < p.length; i++) {
		var key = 'answer_' + p[i].hangoutId;
		var answer = gapi.hangout.data.getState()[key];
		answers[i] = answer;
	}
	
	
	
	var cArray = new Array();
	
	var allC = '<hr><table class="answerTable"><tr>';
	for (var i = 0; i < p.length; i++) {
		allC += '<td><b>Answer '+(i+1)+':</b></td>';
	}
	
	allC += '</tr><tr>';
	
	for (var i = 0; i < p.length; i++) {
	
		var c = '';
	
		var key = 'answer_' + p[i].hangoutId;
		var answer = gapi.hangout.data.getState()[key];

		c += answer;
		
		if (gapi.hangout.data.getState()['turnId'] != sourceId) {
			c += '<br/><input type="button" name="voteButton" class="voteButton" value="Vote" onClick="voteForAnswer(&#39;'+sourceId+'&#39;,&#39;'+p[i].hangoutId+'&#39;)"/>';
		}
					
		c += '<br/><div id="voteResult_'+p[i].hangoutId+'" class="votedDiv"><b>Votes:</b></div>';
				
		cArray[i] = c;
	}
	cArray.sort(function() {return 0.5 - Math.random()});
	
	for (var i = 0; i < cArray.length; i++) {
		allC += '<td>'+cArray[i]+'</td>';
	}
	
	allC += '</tr></table>';
		
	document.getElementById('answerDisplayDiv').innerHTML = allC;
	document.getElementById('answerDisplayDiv').style.display = 'block';
}

function voteForAnswer(sourceId, targetId) {
	
	var sourceP = gapi.hangout.getParticipantById(sourceId);
	
	var key = 'vote_'+sourceP.hangoutId;
	if (!gapi.hangout.data.getState()[key]) {
		
		var voteButtons = document.getElementsByName('voteButton');
		for (var i = 0; i < voteButtons.length; i++) {
			voteButtons[i].style.visibility='hidden';
		}
		
		var targetP = gapi.hangout.getParticipantById(targetId);
		console.log(sourceP.displayName+' voted for '+targetP.displayName);
		
		var totalVotes = 0;
		var totalVotesKey = 'totalVotes_'+targetId;
		if (gapi.hangout.data.getState()[totalVotesKey]) {
			totalVotes = parseInt(gapi.hangout.data.getState()[totalVotesKey]);
		}
		totalVotes++;
		
		var delta = {};
		delta[key] = targetId;
		delta[totalVotesKey] = ''+totalVotes;
		
		gapi.hangout.data.submitDelta(delta);
	}
}

function writeVote(added) {
	
	var sourceId = added.key.substring(5);
	var sourceP = gapi.hangout.getParticipantById(sourceId);
	
	var thediv = document.getElementById('voteResult_'+added.value);
	thediv.innerHTML += '<br/>' + sourceP.displayName;
}


function checkDoneVoting() {
	var p = gapi.hangout.getParticipants();
	
	for (var i = 0; i < p.length; i++) {
		var key = 'vote_' + p[i].hangoutId;
		if (gapi.hangout.data.getState()['turnId'] != p[i].hangoutId && !gapi.hangout.data.getState()[key]) {
			console.log("Not all votes have been recieved. Missing: "+key);
			return;
		}
	}
	
	console.log("All Votes Recieved!!!");
	tallyVote();
	
	if (gapi.hangout.data.getState()['turnId'] == gapi.hangout.getParticipantId()) {
		document.getElementById('nextTurnDiv').style.display = 'block';
	}
	
	var turnId = gapi.hangout.data.getState()['turnId']
	var correct = gapi.hangout.data.getState()['answer_'+turnId];
	
	document.getElementById('correctDiv').innerHTML = 'Correct Answer: ' + correct;
	document.getElementById('correctDiv').style.display = 'block';
}

function tallyVote() {
	
	var turnId = gapi.hangout.data.getState()['turnId'];
	
	var sourceId = gapi.hangout.getParticipantId();
	var sourceP = gapi.hangout.getParticipantById(sourceId);
	
	var score = 0;
	var scorekey = 'score_' + sourceId;
	if (gapi.hangout.data.getState()[scorekey]) {
		score = parseInt(gapi.hangout.data.getState()[scorekey]);
	}
	
	if (turnId == sourceId) {
		var totalkey = 'totalVotes_' + sourceId;
		if (!gapi.hangout.data.getState()[totalkey]) {
			score += 3;
		}
	}
	else {
		var votekey = 'vote_' + sourceId;
		if (gapi.hangout.data.getState()[votekey] == turnId) {
			console.log(sourceP.displayName + ' voted for correct answer');
			score += 2;
		}
		
		var totalkey = 'totalVotes_' + sourceId;
		if (gapi.hangout.data.getState()[totalkey]) {
			var votes = parseInt(gapi.hangout.data.getState()[totalkey]);
			console.log(sourceP.displayName + ' had ' +votes+ ' votes');
			score += votes;
		}
	}
	
	var delta = {};
	delta[scorekey] = ''+score;
	gapi.hangout.data.submitDelta(delta);
}

function tallyVotes() {
	
	var scores = getScores();
	
	var turnId = gapi.hangout.data.getState()['turnId'];
	
	var p = gapi.hangout.getParticipants();
	
	for (var i = 0; i < p.length; i++) {
		var key = 'vote_' + p[i].hangoutId;
		if (gapi.hangout.data.getState()[key] == turnId) {
			console.log(p[i].displayName + ' voted for correct answer');
			addScore(p[i].hangoutId, 2);
		}
	}
	
	for (var i = 0; i < p.length; i++) {
		var key = 'totalVotes_' + p[i].hangoutId;
		if (gapi.hangout.data.getState()[key]) {
			var votes = parseInt(gapi.hangout.data.getState()[key]);
			console.log(p[i].displayName + ' had ' +votes+ ' votes');
			addScore(p[i].hangoutId, votes);
		}
	}
	
	writeScores();
}

function getScores() {
	
	var scores = {};
	
	var p = gapi.hangout.getParticipants();
	
	for (var i = 0; i < p.length; i++) {
		var score = 0;
		var key = 'score_' + p[i].hangoutId;
		if (gapi.hangout.data.getState()[key]) {
			score = parseInt(gapi.hangout.data.getState()[key]);
		}
		
		scores[key] = score;
	}
	
	return scores;
}

function getScore(id) {
	var score = 0;
	var key = 'score_' + id;
	if (gapi.hangout.data.getState()[key]) {
		score = parseInt(gapi.hangout.data.getState()[key]);
	}
	return score;
}

function addScore(id, points) {
	var key = 'score_' + id;
	var score = getScore(id);
	
	score += points;
	
	return score;
}

function writeScores() {
	var c = '<b>Scorecard</b>';
	
	var p = gapi.hangout.getParticipants();
	
	for (var i = 0; i < p.length; i++) {
		
		var score = getScore(p[i].hangoutId);
		
		c += '<br/>';
		c += p[i].displayName + ': ' + score;
	}
	
	document.getElementById('scoreDiv').innerHTML = c;
}


// Callback functions for events created by the hangout
function apiReady() {
  console.log("API is ready");
}


function resetDisplay() {
	document.getElementById('nextTurnDiv').style.display = 'none';
	document.getElementById('correctDiv').style.display = 'none';
	
	document.getElementById('questionText').value = '';
	document.getElementById('questionBoxDiv').style.display = 'none';
	
	document.getElementById('questionDisplayDiv').innerHTML = '';
	document.getElementById('questionDisplayDiv').style.display = 'none';
	
	document.getElementById('answerText').value = '';
	document.getElementById('answerBoxDiv').style.display = 'none';
	
	document.getElementById('answerDisplayDiv').innerHTML = '';
	document.getElementById('answerDisplayDiv').style.display = 'none';
	
	
}

function nextTurn() {
	
	var state = gapi.hangout.data.getState();
	
	for (key in state) {
		if (key.indexOf('turn') == 0 || key.indexOf('score_') == 0 || key == 'firstPlayer') {
			
		}
		else {
			gapi.hangout.data.submitDelta({},[key]);
		}
	}
}

function stateUpdated(adds, removes, delta, metadata) {

	if (adds != null && adds.length > 0) {
		console.log("Added to state: ");
		for (var i = 0; i < adds.length; i++) {
			console.log("\t"+adds[i].key+": "+adds[i].value);
			
			var added = adds[i];
			
		  if (added.key == 'question') {
			  createContentAfterQuestion();
		  }
		  else if (added.key.indexOf('answer_') == 0) {
			  createContentAfterAnswer();
		  }
		  else if (added.key.indexOf('vote_') == 0) {
			  writeVote(added);
			  checkDoneVoting();
		  }
		  else if (added.key.indexOf('score_') == 0) {
			  writeScores();
		  }
		  else if (added.key == 'turnId') {
			  createContentBeforeQuestion();
		  }
		}
	}
	if (removes != null && removes.length > 0) {
		console.log("Removed from state: ");
		for (var i = 0; i < removes.length; i++) {
			console.log("\t"+removes[i]);
		}
		
		resetDisplay();
		determineTurn();
	}
}

function participantsUpdated(participantsArray) {
  //console.log("Participants count: " + participantsArray.length);
  //var participantsListElement = document.getElementById('participants');
  //participantsListElement.innerHTML = participantsArray.length;
}


// A function to be run at app initialization time which registers our callbacks
function init() {
		
  console.log("Init app.");
  gapi.hangout.data.addStateChangeListener(stateUpdated);
  gapi.hangout.addParticipantsListener(participantsUpdated);

  // This application is pretty simple, but use this special api ready state
  // event if you would like to any more complex app setup.
  gapi.hangout.addApiReadyListener(apiReady);  
}

function randomSort(a,b) {
    // Get a random number between 0 and 10
    var temp = parseInt( Math.random()*10 );

    // Get 1 or 0, whether temp is odd or even
    var isOddOrEven = temp%2;

    // Get +1 or -1, whether temp greater or smaller than 5
    var isPosOrNeg = temp>5 ? 1 : -1;

    // Return -1, 0, or +1
    return( isOddOrEven*isPosOrNeg );
}




gadgets.util.registerOnLoadHandler(init);

